const app = getApp();
var openid = wx.getStorageSync('openid');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pets:[],
    sexArray:['保密','男','女'],
    region:['北京市','北京市','朝阳区'],
    petIndex:'0',
    openid: openid,
    nick: '',
    username: '',
    sex: '0',
    age: '',
    brith: '',
    city: '',
    pet: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    wx.request({
      url: app.config.serverCfg.domain.cate,
      data: {
        page: '1',
        size: '20'
      },
      success(res) {
        that.setData({
          pets: res.data.data,
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    openid = wx.getStorageSync('openid');
    var common = require('../../../utils/common.js');
    if (!openid) {
      common.getToLogin();
      return false;
    }
    //获取用户资料
    var that = this;
    if (openid) {
      wx.request({
        url: app.config.serverCfg.domain.myInfo,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: { openid: openid },
        success(res) {
          if (res.data.retcode == 2000000) {
            if (res.data.data.bindMobile == true) {
              that.setData({ 
                age: res.data.data.age,
                sex: res.data.data.gender,
                nick: res.data.data.nick,
                username: res.data.data.username
              })
            }
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 获取表单的值
   */
  changeInput(e) {
    var that = this;
    let changed = {};
    let prop = e.currentTarget.dataset.prop;
    changed[prop] = e.detail.value;
    if (prop == 'city') {
      this.setData({'region':e.detail.value});
      this.setData({ 'city': e.detail.value[1] });
      return true;
    }
    if (prop == 'pet') {
      this.setData({ 'pet': that.data.pets[e.detail.value]['id'] });
      this.setData({ 'petIndex': e.detail.value});
      return true;
    }
    this.setData(changed)
  },
  /**
 * 提交数据
 */
  postData: function () {
    var that = this;
    wx.request({
      url: app.config.serverCfg.domain.myUserAdd,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: that.data,
      success(res) {
        var msg = '更新成功';
        if (res.data.retcode != 2000000) {
          msg = res.data.msg;
        }
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  }
})